package cn.itrip.auth.service.token;

import cn.itrip.beans.pojo.ItripUser;
import cn.itrip.beans.vo.ItripTokenVO;
import cn.itrip.common.DateUtil;
import cn.itrip.common.MD5;
import cn.itrip.common.RedisAPI;
import cn.itrip.common.UserAgentUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.Date;

/**
 * TokenServiceImpl class
 *
 * @author Administrator
 * @date 2021/7/2
 */
@Service
public class TokenServiceImpl implements TokenService {
    @Resource
    private RedisAPI redisAPI;
    @Override
    public ItripTokenVO generateToken(ItripUser user, String userAgent) {
        StringBuilder tokenBuilder = new StringBuilder(TOKEN_PREFIX);
        // 根据userAgent来判断是移动端还是PC端
        boolean isMobile = UserAgentUtil.checkAgent(userAgent);
        if(isMobile) {
            tokenBuilder.append(FLAG_MOBILE);
        }else{
            tokenBuilder.append(FLAG_PC);
        }
        tokenBuilder.append(TOKEN_DELIMITER);
        // 拼接userCode的32位md5值
        String md5 = MD5.getMd5(user.getUserCode(), 32);
        tokenBuilder.append(md5);
        tokenBuilder.append(TOKEN_DELIMITER);
        // 拼接userId
        tokenBuilder.append(user.getId());
        tokenBuilder.append(TOKEN_DELIMITER);
        // 拼接创建时间
        Date generateTime = new Date();
        try {
            tokenBuilder.append(DateUtil.format(generateTime,"yyyyMMddHHmmss"));
            tokenBuilder.append(TOKEN_DELIMITER);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        // 根据userAgent生成一段md5,作为浏览器的一个识别数据
        tokenBuilder.append(MD5.getMd5(userAgent,6));
        // 返回token值
        ItripTokenVO tokenVO = new ItripTokenVO();
        tokenVO.setToken(tokenBuilder.toString());
        tokenVO.setGenTime(generateTime.getTime());
        tokenVO.setExpTime(generateTime.getTime()+SESSION_TIMEOUT*1000);
        return tokenVO;
    }

    @Override
    public boolean save(String token, ItripUser user) {
        if(isMobileToken(token)){
            return redisAPI.set(token, JSON.toJSONString(user));
        }else{
            return redisAPI.set(token, SESSION_TIMEOUT,JSON.toJSONString(user));
        }
    }
    private boolean isMobileToken(String token){
        return token.startsWith(TOKEN_PREFIX+FLAG_MOBILE);
    }

}
